import time
import taskConfig

class taskManager:
    taskFile        = None
    logFile         = None
    logFP           = None
    taskTodo        = {}
    taskAssigned    = {}
    lastResponse    = {}

    def __init__(self, taskFile, logFile=None):
        self.taskFile   = taskFile
        self.logFile    = logFile
        
        if self.logFile != None:
            self.logFP  = open(self.logFile, 'a+')
        
    def taskLoad(self):
        fp          = open(self.taskFile, 'r')
        tasks       = fp.readlines()
        doneTasks   = self.logFP.readlines()
        for task in tasks:
            done    = False
            for doneTask in doneTasks:
                if task.strip(' \r\t\n') == doneTask.strip(' \t\r\n'):
                    done = True
            if done == False:
                self.taskTodo [task.strip(' \t\r\n')]   = False
        fp.close()

    def taskPrint(self):
        print self.taskDict
    
    def nextTask(self):
        for key in self.taskTodo.keys():
            if self.taskTodo [key] is False:
                try:
                    if self.taskAssigned [key] is True:
                        pass
                except KeyError:
                    self.taskAssigned [key] = True
                    self.iAmAlive(key)
                    print 'Task Assigned: ' + key
                    return key

        return 'NONE'

    def iAmAlive(self, key):
        self.lastResponse [key] = int(time.time())

    def whoIsDead(self):
        currentTime = int(time.time())
        for assignKey in self.taskAssigned.keys():
            timeDiff    = currentTime - self.lastResponse [assignKey]
            if timeDiff > taskConfig.taskHeartBeatTimeOut:
                ''' It means the client has stopped responding
                    Remove it from the task assigned list and 
                    add it to the ToDo task list.
                '''
                self.updateStatus('FAIL', assignKey)
    
    def updateStatus(self, status, key):
        try:
            if status == 'FAIL':
                del self.taskAssigned [key]
            
            if status == 'SUCCESS':
                del self.taskAssigned [key]
                self.taskTodo [key] = True  
                self.logFP.write(key + '\n')
                self.logFP.flush()
                print 'updateStatus: Done= ' + key
        except KeyError:
            print 'Key Error'
            pass
